<script setup>
import { useAppStore, useWMSStore } from '@/stores'
import * as monaco from 'monaco-editor'

const appStore = useAppStore()
const wmsStore = useWMSStore()
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)

const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(187) : ref(227)) : appStore.showFooter ? ref(227) : ref(272)

const computedHeight = computed(() => windowHeight.value - adaptHeight.value)
let editor = null
const code = ref(`
window.smViewer_wms = new SuperMap3D.Viewer('SuperMap3DContainer')

// 星图地球云影像
smViewer_wms.imageryLayers.addImageryProvider(
  new SuperMap3D.UrlTemplateImageryProvider({
    url: 'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=68a7e91671f4ff9d03068c85ec2660af69558c60929c0e644aba6a342735e2dc', //服务地址
    maximumLevel: 18,
    subdomains: '123'
  })
)`)

const resetCode = () => {
  const model = editor.getModel()
  model.setValue(wmsStore.supermap3dAddCode)
  setTimeout(() => editor.getAction('editor.action.formatDocument').run(), 800)
}

const runCode = () => {
  editor.getAction('editor.action.formatDocument').run()
  try {
    eval(toRaw(editor).getValue())
  } catch (error) {
    window.$message.error(extractKeyInfo(error))
  }
}

function extractKeyInfo(message) {
  const match = JSON.stringify(message).match(/^(?:Error: )(.+?)\./)
  return match ? match[1] : 'No error info found'
}

const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
  editor = monaco.editor.create(document.getElementById('editorContainer'), {
    value: code.value, // 编辑器初始显示文字
    language: 'javascript', // 语言支持自行查阅demo
    automaticLayout: true, // 自适应布局
    // theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
    foldingStrategy: 'indentation', // 代码可分小段折叠
    renderLineHighlight: 'all', // 行亮
    selectOnLineNumbers: true, // 显示行号
    minimap: {
      enabled: false
    },
    readOnly: false, // 只读
    fontSize: 14, // 字体大小
    scrollBeyondLastLine: false, // 取消代码后面一大段空白
    overviewRulerBorder: false, // 不要滚动条的边框
    wordWrap: 'on', // 自动换行
    tabSize: 2 // tab 缩进长度
  })
  editor.getAction('editor.action.formatDocument').run()
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(
  () => wmsStore.supermap3dAddCode,
  () => {
    const model = editor.getModel()
    model.setValue(`
${code.value}
${wmsStore.supermap3dAddCode}
    `)
    setTimeout(() => editor.getAction('editor.action.formatDocument').run(), 800)
  }
)
watch(
  () => appStore.colorMode,
  () => (appStore.colorMode === 'light' ? monaco.editor.setTheme('vs') : monaco.editor.setTheme('vs-dark')),
  { immediate: true }
)
watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)
watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card title="加载代码">
    <template #header-extra>
      <n-button type="primary" quaternary @click="resetCode">
        <template #icon>
          <icon-park-outline-refresh />
        </template>
        重置
      </n-button>
      <n-button type="primary" quaternary @click="runCode">
        <template #icon>
          <icon-park-outline-link-cloud />
        </template>
        运行
      </n-button>
    </template>
    <n-infinite-scroll>
      <div id="editorContainer" :style="{ height: `${computedHeight}px` }"></div>
    </n-infinite-scroll>
  </n-card>
</template>
